package com.cspg.design.ui.advise;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.cspg.design.R;
import com.cspg.design.dto.ElectrifiedData;
import com.cspg.design.presenter.ProjectPresenter;
import com.cspg.design.utils.ActionBarUtil;
import com.cspg.design.utils.AppManager;
import com.cspg.design.utils.StatusBarUtil;
import com.cspg.design.widget.ToastUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.zip.Inflater;

public class LiveWorkingActivity extends AppCompatActivity implements View.OnClickListener {

    private TableLayout firstTable;
    private TableLayout secondTable;
    private int firstOrderNumber = 1;
    private int secondOrderNumber = 1;
    private ProjectPresenter projectPresenter;
    private String projectID;
    Calendar calendar= Calendar.getInstance(Locale.CHINA);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_live_working);
        StatusBarUtil.setStatusBarColor(this, R.color.colorPrimary);
        ActionBarUtil.setActionBar(this, R.string.working_plan);
        AppManager.getAppManager().addActivity(this);
        firstTable = findViewById(R.id.first_tb);
        secondTable = findViewById(R.id.second_tb);
        Button firstBtn = findViewById(R.id.first_btn);
        firstBtn.setOnClickListener(this);
        Button seconBtn = findViewById(R.id.second_btn);
        seconBtn.setOnClickListener(this);
        Button saveBtn = findViewById(R.id.live_working_save);
        saveBtn.setOnClickListener(this);
        projectPresenter = new ProjectPresenter(this);
        projectID = getIntent().getStringExtra("projectId");

        EditText jobTimeEt = findViewById(R.id.live_working_job_time);
        jobTimeEt.setFocusable(false);
        jobTimeEt.setSelected(false);

        jobTimeEt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog(LiveWorkingActivity.this,4,jobTimeEt,calendar);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.first_btn:
                firstOrderNumber++;
                View view = LayoutInflater.from(this).inflate(R.layout.layout_live_working_tb_first_item, null);
                setTableRow((TableRow) view, "first");
                firstTable.addView(view);
                break;
            case R.id.second_btn:
                secondOrderNumber++;
                View view2 = LayoutInflater.from(this).inflate(R.layout.layout_live_working_second_item, null);
                setTableRow((TableRow) view2, "second");
                secondTable.addView(view2);
                break;
            case R.id.live_working_save:
                saveData();
                break;
        }
    }

    private void setTableRow(TableRow tableRow, String type) {
        int count = tableRow.getChildCount();
        for (int i = 0; i < count; i++) {
            View view = tableRow.getChildAt(i);
            TextView textView = (TextView) view;
            if (textView != null) {
                if (type.equals("first")) {
                    textView.setText(firstOrderNumber + "");
                } else if (type.equals("second")) {
                    textView.setText(secondOrderNumber + "");
                }
                break;
            }
        }
    }

    private void saveData() {
        int count = firstTable.getChildCount();
        List<NewLinePlan> newLinePlanList = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            View view = firstTable.getChildAt(i);
            if (view.getTag().toString().equals("first")) {
                TableRow tableRow = (TableRow) view;
                int trCount = tableRow.getChildCount();
                NewLinePlan newLinePlan = new NewLinePlan();
                for (int j = 0; j < trCount; j++) {
                    View trView = tableRow.getChildAt(j);
                    if (trView.getTag().toString().equals("start")) {
                        EditText editText = (EditText) trView;
                        newLinePlan.StartXJ = editText.getText().toString().trim();
                    } else if (trView.getTag().toString().equals("end")) {
                        EditText editText = (EditText) trView;
                        newLinePlan.EndXJ = editText.getText().toString().trim();
                    } else {
                        continue;
                    }
                }
                newLinePlanList.add(newLinePlan);
            }

        }
        int secondCount = secondTable.getChildCount();
        List<WorkingLinePlan> workingLinePlanList = new ArrayList<>();
        for (int i = 0; i < secondCount; i++) {
            View view = secondTable.getChildAt(i);
            if (view.getTag().toString().equals("second")) {
                TableRow tableRow = (TableRow) view;
                int trCount = tableRow.getChildCount();
                WorkingLinePlan workingLinePlan = new WorkingLinePlan();
                for (int j = 0; j < trCount; j++) {
                    View trView = tableRow.getChildAt(j);
                    if (trView.getTag().toString().equals("start")) {
                        EditText editText = (EditText) trView;
                        workingLinePlan.StartXJ = editText.getText().toString().trim();
                    } else if (trView.getTag().toString().equals("end")) {
                        EditText editText = (EditText) trView;
                        workingLinePlan.EndXJ = editText.getText().toString().trim();
                    } else if (trView.getTag().toString().equals("position")) {
                        EditText editText = (EditText) trView;
                        workingLinePlan.SwitchPosition = editText.getText().toString().trim();
                    } else {
                        continue;
                    }
                }
                workingLinePlanList.add(workingLinePlan);
            }
        }
        EditText jobWayEt = findViewById(R.id.live_working_job_way);
        EditText jobPoleEt = findViewById(R.id.live_working_job_pole);
        EditText jobMethodEt = findViewById(R.id.live_working_job_method);
        EditText jobTimeEt = findViewById(R.id.live_working_job_time);
        EditText jobDeviceEt = findViewById(R.id.live_working_job_device);
        ElectrifiedData electrifiedData = new ElectrifiedData();
        electrifiedData.setNewLine(JSONObject.toJSONString(newLinePlanList));
        electrifiedData.setWorkingLine(JSONObject.toJSONString(workingLinePlanList));
        electrifiedData.setJobWay(jobWayEt.getText().toString().trim());
        electrifiedData.setJobPole(jobPoleEt.getText().toString().trim());
        electrifiedData.setJobMethod(jobMethodEt.getText().toString().trim());
        electrifiedData.setJobDevice(jobDeviceEt.getText().toString().trim());
        electrifiedData.setJobTime(jobTimeEt.getText().toString().trim());


        String json = JSONObject.toJSONString(electrifiedData);
        System.out.println(json);
        if (projectID == null || projectID.isEmpty())
        {
            ToastUtils.toast(this,"项目ID获取错误。。。");
            return;
        }
        projectPresenter.postProjectElectrifiedSubmit(projectID,json);

    }

    private class NewLinePlan implements Serializable {
        public String StartXJ;
        public String EndXJ;
    }

    private class WorkingLinePlan implements Serializable {
        public String StartXJ;
        public String EndXJ;
        public String SwitchPosition;
    }

    /**
     * 日期选择
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    public static void showDatePickerDialog(Activity activity, int themeResId, final TextView tv, Calendar calendar) {
        // 直接创建一个DatePickerDialog对话框实例，并将它显示出来
        new DatePickerDialog(activity, themeResId, new DatePickerDialog.OnDateSetListener() {
            // 绑定监听器(How the parent is notified that the date is set.)
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // 此处得到选择的时间，可以进行你想要的操作
                tv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth );
            }
        }
                // 设置初始日期
                , calendar.get(Calendar.YEAR)
                , calendar.get(Calendar.MONTH)
                , calendar.get(Calendar.DAY_OF_MONTH)).show();
    }

}